import TyOverlayexLayer from './TyOverlayexLayer'
import TyLabel from './TyLabel'
import Collection from 'ol/Collection'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import Modify from 'ol/interaction/Modify'
import {Polygon} from 'ol/geom'
import Draw from 'ol/interaction/Draw'
import {shiftKeyOnly, singleClick} from 'ol/events/condition'
import {createRegularPolygon} from 'ol/interaction/Draw'

/**
 * 手工绘图工具
 * @param map 地图
 * @param drawedStyle 绘制完成后的样式
 * @param sketchStyle 绘画时的样式 默认为空，用系统样式
 * @param modifyStyle 修改feature时的样式
 * @returns {{start: start, clear: clear, close: close, setStyle: setStyle, getFeatures: (function(): Array<module:ol/Feature>)}}
 * @constructor
 */
class DrawTool {
  constructor(map, drawedStyle, sketchStyle, modifyStyle) {
    this.map = map
    this.drawedStyle = drawedStyle
    this.sketchStyle = sketchStyle
    this.modifyStyle = modifyStyle
    this.draw = null
    this.features = new Collection()// 很重要！！！

    this.vecSource = new VectorSource({
      features: this.features,
      useSpatialIndex: false,
      wrapX: false
    })
    this.vecLayer = new VectorLayer({
      style: drawedStyle,
      source: this.vecSource,
      map: this.map
    })
    this.modify = new Modify({
      features: this.features,
      style: modifyStyle,
      deleteCondition: function(event) {
        return shiftKeyOnly(event) && singleClick(event)
      }
    })
    this.map.addInteraction(this.modify)
    this.overlayexLayer = new TyOverlayexLayer({
      id: 'TyMapUtils.DrawTool',
      map: this.map
    })
  }

  /**
   * type 点 线 多边形 圆形 方形：Point LineString Polygon Circle Square  Box
   * drawEndCallback 返回事件
   */
  start(type, drawEndCallback) {
    let value = type
    if (this.draw) {
      this.draw.un('drawend', drawEndCallback)
      this.map.removeInteraction(this.draw)
    }
    // addInteraction()

    // function addInteraction() {

      if (value !== 'None') {
        let geometryFunction
        let maxPoints
        if (value === 'Square') {
          value = 'Circle'
          geometryFunction = createRegularPolygon(4)
        } else if (value === 'Box') {
          value = 'LineString'
          maxPoints = 2
          geometryFunction = function(coordinates, geometry) {
            if (!geometry) {
              geometry = Polygon(null)
            }
            const start = coordinates[0]
            const end = coordinates[1]
            geometry.setCoordinates([
              [start, [start[0], end[1]], end, [end[0], start[1]], start]
            ])
            return geometry
          }
        }
        this.draw = new Draw({
          features: this.features,
          type: /** @type {ol.geom.GeometryType} */ (value),
          geometryFunction: geometryFunction,
          maxPoints: maxPoints,
          style: this.sketchStyle
        })
        if (this.draw) {
          this.map.addInteraction(this.draw)
          this.draw.on('drawend', (e) => {
            // 插入一个用于删除feature的X
            const geom = e.feature.getGeometry()
            const pos = geom.getLastCoordinate()
            const label = new TyLabel('✖', {
              // id: newId,
              position: pos,
              offset: [-10, -10],
              positioning: 'bottom-center',
              style: { backgroundColor: '#ffffff', fontSize: 12, fontName: 'arial', border: '1px solid rgb(0, 0, 0)' }
            })
            this.overlayexLayer.addOverlayex(label)

            // 这里只能选择mousedown，并阻止其冒泡，因为绘画过程中，mousedown开始绘制，所以要防止；
            label.addEventListener('mousedown', (overlayex, evt) => {
              evt.stopEvent = true// 阻止冒泡；
              this.overlayexLayer.removeOverlayex(overlayex)
              this.features.remove(e.feature)
            })
            drawEndCallback(e)// 调用回调函数 ；
          })
        }
      }
    // }
  }

  clear() {
    this.vecSource.clear()
    this.overlayexLayer.clear()
  }

  getFeatures() {
    return this.vecSource.getFeatures()
  }
  setStyle = function(style) {
    this.sketchStyle = style
  }
  close() {
    if (this.draw) {
      this.map.removeInteraction(this.draw)
      this.draw = null
    }
    if (this.modify) {
      this.map.removeInteraction(this.modify)
      this.modify = null
    }
    this.vecSource.clear()
    this.map.removeLayer(this.vecLayer)
    this.overlayexLayer.clear()
  }
}

export default DrawTool
